const http = require('http')
const fs = require('fs')
const querystring = require('querystring')
const urlLib = require('url')

var users = {};

http.createServer(function(req, res) {

    // POST
    let str = ''

    req.on('data', data => {
        str += data
    })

    req.on('end', () => {
        const obj = urlLib.parse(req.url, true)
        
        const url = obj.pathname
        const GET = obj.query
        const POST = querystring.parse(str)

        if (url == '/user') {
            console.log(POST);

            switch(POST.act) {
                case 'reg':
                    // 1. 检查用户是否存在
                    // 2. 插入USER
                    if (users[POST.user]) {
                        res.write('{"err":555,"err_msg":"用户已存在"}')
                    } else {
                        users[POST.user] = POST.pass;
                        res.write('{"err":0,"err_msg":"注册成功"}')
                    }
                    break;
                case 'login':
                    // 1. 检查用户是否存在
                    // 2. 检查用户密码
                    if (!users[POST.user]) {
                        res.write('{"err":555,"err_msg":"此用户不存在"}')
                    } else if(users[POST.user] != POST.pass) {
                        res.write('{"err":555,"err_msg":"用户或密码错误"}')
                    } else {
                        res.write('{"err":0,"err_msg":"登录成功"}')
                    }
                    break;
                default: 
                    res.write('{"err":404,"err_msg":"not found"}')
            }
                
            res.end();

        } else {

            // read file
            let file_name = './www' + url
            fs.readFile(file_name, (err, data) => {
                if(err) {
                    res.write('404')
                } else {
                    res.write(data)
                }

                res.end();
            })
            
        }

    })

}).listen(8080)